package cn.laixueit.controller;

import cn.laixueit.pojo.Photo;
import cn.laixueit.service.PhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/photo")
public class PhotoController {

    @Autowired
    private PhotoService photoService;

    @PostMapping("/img")
    public String img(@RequestParam("img")MultipartFile[] file, HttpSession session){

        String realPath = session.getServletContext().getRealPath("/img");

        File filePath = new File(realPath);
        if(!filePath.exists()){
            filePath.mkdirs();
        }

        for (MultipartFile f : file) {
            String originalFilename = f.getOriginalFilename();
            originalFilename = UUID.randomUUID().toString()+originalFilename;
            File dirFile = new File(realPath, originalFilename);
            try {
                f.transferTo(dirFile);

                Photo photo = new Photo();
                photo.setImgurl("/img/"+originalFilename);
                photoService.add(photo);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "redirect:/home.do";
    }
}
